# -*- coding: utf-8 -*-

import random as ran
from numpy import array

class Nuclear:
    def __init__(self):
        self.score = 0
        self.data = [[], [], [], []]
        for i in range(16):
            row = i // 4
            self.data[row].append(0)
        self.data[ran.randint(0, 3)][ran.randint(0, 3)] = ran.choice([2, 2, 2, 2, 4])
        self.put()
        self.display()
        self.align("D")
        self.display()
        ######################
        # TODO: put a number #
        ######################
        
    def _align(self, data):
        sc_get = 0
        temp = []
        for row in data:
            row = [x for x in row if x]
            for i in range(len(row) - 1):
                if row[i] == row[i + 1]:
                    row[i] += row[i]
                    row[i + 1] = 0
                    sc_get += row[i]
            row = [x for x in row if x]
            while len(row) < 4:
                row.append(0)
            temp.append(row)
        return sc_get, temp
    
    
    def _redire(self, data):
        temp = []
        for row in data:
            temp.append(row[::-1])
        return temp
    
    
    def align(self, dire):
        t = self.data
        s = 0
        if dire == "R":
            t = self._redire(self.data)
        elif dire == "U":
            t = array(self.data).T.tolist()
        elif dire == "D":
            t = self._redire(array(self.data).T.tolist())
        s, temp = self._align(t)
        if temp != self.data:
            if dire == "R":
                t = self._redire(temp)
            elif dire == "U":
                t = array(temp).T.tolist()
            elif dire == "D":
                t = array(self._redire(temp)).T.tolist()
            self.score = s
            self.data = t
            return True
        else:
            return False
        
        
    def put(self):
        v = 1
        i = j = 0
        while(v):
            i = ran.randint(0, 3)
            j = ran.randint(0, 3)
            v = self.data[i][j]
        self.data[i][j] = ran.choice([2, 2, 2, 2, 4])
    
    def display(self):
        '''显示界面

        '''
        print('{0:4} {1:4} {2:4} {3:4}'.format(self.data[0][0], self.data[0][1], self.data[0][2], self.data[0][3]))
        print('{0:4} {1:4} {2:4} {3:4}'.format(self.data[1][0], self.data[1][1], self.data[1][2], self.data[1][3]))
        print('{0:4} {1:4} {2:4} {3:4}'.format(self.data[2][0], self.data[2][1], self.data[2][2], self.data[2][3]))
        print('{0:4} {1:4} {2:4} {3:4}'.format(self.data[3][0], self.data[3][1], self.data[3][2], self.data[3][3]))
        print('   Total score: ', self.score)
        
if __name__ == "__main__":
    g = Nuclear()
    